package com.hbzhit.modules.sys.controller;

import com.hbzhit.common.enums.TokenTypeEnum;
import com.hbzhit.common.utils.IPUtils;
import com.hbzhit.common.utils.R;
import com.hbzhit.modules.sys.entity.SysUserEntity;
import com.hbzhit.modules.sys.service.ShiroService;
import com.hbzhit.modules.sys.service.SysCaptchaService;
import com.hbzhit.modules.sys.service.SysLogService;
import com.hbzhit.modules.sys.service.SysUserService;
import com.hbzhit.modules.sys.vo.SysLoginVO;
import com.hbzhit.modules.wx.service.WxUserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.AllArgsConstructor;
import org.apache.commons.io.IOUtils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.crypto.hash.Sha256Hash;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.imageio.ImageIO;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.awt.image.BufferedImage;
import java.io.IOException;

/**
 * 登录相关
 *
 * @author Mark sunlightcs@gmail.com
 */
@Api(tags = {"登录相关API"})
@AllArgsConstructor
@RestController
@RequestMapping("/login")
public class SysLoginController {

    private final SysUserService sysUserService;
    private final ShiroService shiroService;
    private final SysCaptchaService sysCaptchaService;
    private final SysLogService sysLogService;
    @Resource
    private WxUserService wxUserService;

    /**
     * 验证码
     */
    @ApiOperation(value = "获取验证码")
    @GetMapping("captcha.jpg")
    public void captcha(@ApiParam(value = "验证码唯一id", required = true) String uuid, HttpServletResponse response) throws IOException {
        response.setHeader("Cache-Control", "no-store, no-cache");
        response.setContentType("image/jpeg");

        //获取图片验证码
        BufferedImage image = sysCaptchaService.getCaptcha(uuid);

        ServletOutputStream out = response.getOutputStream();
        ImageIO.write(image, "jpg", out);
        IOUtils.closeQuietly(out);
    }

    /**
     * 后台登录
     */
    @ApiOperation(value = "后台登录")
    @PostMapping("/sys")
    public R<Object> sysLogin(@RequestBody SysLoginVO form, HttpServletRequest request) {
        SysUserEntity user = shiroService.login(form, TokenTypeEnum.SYS.getValue(), IPUtils.getIpAddr(request));
        return R.ok()
                .put("user", user)
                .put("token", SecurityUtils.getSubject().getSession().getId());
    }

    /**
     * APP登录
     */
    @ApiOperation(value = "APP登录")
    @PostMapping("/app")
    public R<Object> appLogin(@RequestBody SysLoginVO form, HttpServletRequest request) {
        SysUserEntity user = shiroService.login(form, TokenTypeEnum.APP.getValue(), IPUtils.getIpAddr(request));
        return R.ok()
                .put("user", user)
                .put("token", SecurityUtils.getSubject().getSession().getId());
    }

    /**
     * 第三方登录
     */
    @ApiOperation(value = "第三方登录")
    @PostMapping("/other")
    public R<Object> otherLogin(@RequestBody SysLoginVO form, HttpServletRequest request) {
        SysUserEntity user = shiroService.login(form, form.getTokenType(), IPUtils.getIpAddr(request));
        return R.ok()
                .put("user", user)
                .put("token", SecurityUtils.getSubject().getSession().getId());
    }

    /**
     * 第三方账号绑定
     */
    @ApiOperation(value = "第三方账号绑定")
    @PostMapping("/other/bind")
    public R<Object> otherBind(@RequestBody SysUserEntity params) {
        // 账号是否存在
        SysUserEntity user = sysUserService.queryByUserName(params.getUsername());
        if (user == null || user.getId() == null) {
            return R.error("账号不存在");
        }

        //sha256加密
        String password = new Sha256Hash(params.getPassword(), user.getSalt()).toHex();
        if (!user.getPassword().equals(password)) {
            return R.error("密码不正确");
        }
        // 绑定
        user.setOpenid(params.getOpenid());
        sysUserService.getBaseMapper().updateById(user);

        return R.ok(user);
    }


    /**
     * 第三方账号解绑
     */
    @ApiOperation(value = "第三方账号解绑")
    @PostMapping("/other/unbind/{userId}")
    public R otherUnbind(@PathVariable("userId") Long userId) {
        // 账号是否存在
        SysUserEntity user = sysUserService.getById(userId);
        if (user == null || user.getId() == null) {
            return R.error("账号不存在");
        }
        // 解绑
        user.setOpenid("");
        sysUserService.getBaseMapper().updateById(user);

        // 退出登录
        SecurityUtils.getSubject().logout();

        return R.ok();
    }

    /**
     * 退出
     */
    @ApiOperation(value = "后台退出登录")
    @PostMapping("/sys/logout")
    public R sysLogout(HttpServletRequest request) {
        // 记录日志
        SysUserEntity user = (SysUserEntity) SecurityUtils.getSubject().getPrincipal();
        sysLogService.saveLog(user.getId(), "用户登出", IPUtils.getIpAddr(request));
        SecurityUtils.getSubject().logout();

        return R.ok();
    }

    /**
     * 退出
     */
    @ApiOperation(value = "APP退出登录")
    @PostMapping("/app/logout")
    public R appLogout(HttpServletRequest request) {
        // 记录日志
        SysUserEntity user = (SysUserEntity) SecurityUtils.getSubject().getPrincipal();
        sysLogService.saveLog(user.getId(), "用户登出", IPUtils.getIpAddr(request));
        SecurityUtils.getSubject().logout();
        return R.ok();
    }


    @ApiOperation("企业微信登录")
    @GetMapping("/wx/login")
    public R WeChatLogin(@RequestParam String code, HttpServletRequest request) {
        SysLoginVO vo = new SysLoginVO();
        vo.setOpenid(wxUserService.getOpenidByCode(code));
        vo.setTokenType("open");
        SysUserEntity user = shiroService.login(vo, vo.getTokenType(), IPUtils.getIpAddr(request));
        return R.ok()
                .put("user", user)
                .put("token", SecurityUtils.getSubject().getSession().getId());
    }

}
